let express = require("express");
let router = express.Router();
let db = require("../model/db");
const User = db.User;
const crypto = require("crypto");
//添加用户
// 作者:罗涛
router.post("/post", async (req, res) => {
    const md5 = crypto.createHash("MD5");
    req.body.pwd = md5.update(req.body.pwd).digest("hex")
    const data = await db.User.create({
        mobile: req.body.mobile,
        pwd: req.body.pwd,
        isAdmin: req.body.isAdmin
    })
    res.send({
        code: 0,
        message: "",
        data
    });
})
//删除用户
// 作者:罗涛
router.delete("/:id", async (req, res) => {
    const data = await db.User.deleteOne({
        _id: req.params.id
    }); //条件对象
    res.send({
        code: 0,
        message: "",
        data
    });
})
//修改用户
// 作者:罗涛
router.put("/:id", async (req, res) => {
    const md5 = crypto.createHash("MD5");
    req.body.pwd = md5.update(req.body.pwd).digest("hex");
    const data = await db.User.updateOne({
        _id: req.params.id
    }, {
            mobile: req.body.mobile,
            pwd: req.body.pwd,
            isAdmin: req.body.isAdmin
        })
    res.send({
        code: 0,
        message: "",
        data
    });
})
//修改用户权限
// 作者:罗涛
router.put("/isAdmin/:id", async (req, res) => {
    const data = await db.User.updateOne({
        _id: req.params.id
    }, {
            isAdmin: req.body.isAdmin
        })
    res.send({
        code: 0,
        message: "",
        data
    });
})

//查询用户
// 作者:罗涛
router.get("/", async (req, res) => {

    if (!req.query.field) { //默认按照id排序
        req.query.field = "_id";
    }
    if (!req.query.sort) {
        req.query.sort = "asc";
    }
    //拼接排序字符串
    let s = req.query.field;
    if (req.query.sort === "desc") {
        s = "-" + s;
    }
    if (!req.query.page) {
        req.query.page = 1;
    }
    if (!req.query.limit) {
        req.query.limit = 10;
    }

    const page = parseInt(req.query.page);
    const limit = parseInt(req.query.limit);

    let condition = {};
    if (req.query.key) {
        const exp = new RegExp(req.query.key, "i") //不区分大小写
        condition = {
            $or: [{
                mobile: {
                    $regex: exp
                }
            },]
        };
    }
    const data = await db.User.find(condition).sort(s).skip((page - 1) * limit).limit(limit);
    console.log(data);
    res.send({
        "code": 0,
        "msg": "",
        "count": await db.User.count(condition),
        "data": data
    })
})

//查询单个用户
// 作者:罗涛
router.get("/:id", async (req, res) => {
    let data = await db.User.findById(req.params.id);
    res.send(data);
})

//验证用户管理员
// 作者:罗涛 
router.post("/", async (req, res) => {
    const md5 = crypto.createHash("md5");
    req.body.pwd = md5.update(req.body.pwd).digest("hex");
    // 根据传递的账号密码，从数据库中匹配用户，如果找到用户，将用户对象响应，如果没有找到，响应false
    let condition = {
        mobile: req.body.mobile,
        pwd: req.body.pwd,

    }

    let u = await db.User.findOne(condition);
    if (u.isAdmin) {

        //响应的结果中包含cookie
        res.cookie("userId", u._id.toString(), {

            maxAge: 7 * 24 * 60 * 60 * 1000,
            signed: true,
        });
        res.send(true);
    } else {
        res.send(false);
    }
})

//验证用户登录
// 作者:唐松林
router.post("/www", async (req, res) => {
    const md5 = crypto.createHash("md5");
    req.body.pwd = md5.update(req.body.pwd).digest("hex");
    // 根据传递的账号密码，从数据库中匹配用户，如果找到用户，将用户对象响应，如果没有找到，响应false
    let condition = {
        mobile: req.body.mobile,
        pwd: req.body.pwd,
    }
    let u = await db.User.findOne(condition);
    if (u) {

        //响应的结果中包含cookie
        res.cookie("userId", u._id.toString(), {

            maxAge: 7 * 24 * 60 * 60 * 1000,
            signed: true,
        });
        res.send(true);
    } else {
        res.send(false);
    }

})


module.exports = router;